import {ipcMain, shell} from 'electron'
const fs = require('fs');
const path = require('path');
import {appConfig} from "./config"
const { spawn, exec } = require('child_process');


export const fileIPC = () => {
    
    ipcMain.handle('get:vitepress:port', () => {
        const package_file = path.join(appConfig.VITEPRESS_PATH, 'package.json');
        let json = JSON.parse(fs.readFileSync(package_file, 'utf-8'));
        return json.scripts['docs:dev'].split(' ')[5]
    });


    ipcMain.on('open:dir:explorer', (event, relPath) => {
        shell.openPath(path.join(appConfig.VITEPRESS_PATH, relPath))
    });

    ipcMain.on('open:typora', (event, relPath) => {
        const command = `Typora.exe ${path.join(appConfig.VITEPRESS_PATH, 'posts', relPath)}`
        console.log(command)
        exec(command, (err, stdout, stderr) =>{
            if (err) {
                event.reply('exit:typora', {success: false, msg: "Typora 启动失败,请检查是否已安装Typora,并配置环境变量。"})
                return;
            }
            // 如果有标准错误输出，打印
            if (stderr) {
                console.error(`stderr: ${stderr}`);
            }
            
            event.reply('exit:typora', {success: true, msg: 'Typora 启动成功'})
            
        })

    })

    ipcMain.handle('create:dir', async (event, nodeID) => {
        const targetPath = path.join(appConfig.VITEPRESS_PATH, "/posts", nodeID);
    
        try {
            // 检查目录是否存在
            await fs.promises.access(targetPath, fs.constants.F_OK);
            // 如果目录存在，返回失败信息
            return { success: false, msg: `目录 ${nodeID} 已经存在` };
        } catch (err) {
            // 目录不存在，创建目录
            try {
                await fs.promises.mkdir(targetPath);  // 使用异步的 mkdir
                return { success: true, msg: `目录 ${nodeID} 创建成功` };
            } catch (err) {
                // 创建目录失败，返回错误信息
                return { success: false, msg: err.message };
            }
        }
    });

    ipcMain.handle('change:port', (event, port) => {
        try {

            const package_file = path.join(appConfig.VITEPRESS_PATH, 'package.json');
            
            // 2. 检查文件是否存在
            if (!fs.existsSync(package_file)) {
                return { success: true, msg: "出现异常" };
            }
    
            // 3. 读取并解析 package.json
            let json = JSON.parse(fs.readFileSync(package_file, 'utf-8'));

            // 4. 修改 package.json 中的 scripts
            json.scripts['docs:dev'] = `vitepress dev --host 0.0.0.0 --port ${port}`;
    
            // 5. 将修改后的内容写回文件
            fs.writeFileSync(package_file, JSON.stringify(json, null, 4), 'utf-8');
    
            // 返回成功信息
            return { success: true, msg: `端口修改成功，已设置为 ${port}` };
    
        } catch (error) {
            // 捕获并处理错误
            console.error('修改端口时发生错误:', error);
            return { success: false, msg: `端口修改失败: ${error.message}` };
        }
    });

    ipcMain.handle('get:nav:list', async () => {
        const navPath = path.join(appConfig.VITEPRESS_PATH, "/posts");
        const files = await fs.promises.readdir(navPath, { encoding: 'utf-8' });
        return files;
    });

    ipcMain.handle('rename:file', async (event, oldNodeID, newNodeID) => {
        const targetDir = path.join(appConfig.VITEPRESS_PATH, '/posts');
        const oldPath = path.join(targetDir, oldNodeID);
        const newPath = path.join(targetDir, newNodeID);
        if (!fs.existsSync(oldPath)) {
            return {success: false, msg:`文件/目录 ${oldNodeID} 不存在` };
        }
        if (fs.existsSync(newPath)) {
            return {success: false, msg:`目标 ${newNodeID} 已经存在` };
        }
        try {
            fs.renameSync(oldPath, newPath);
            return {success: true, msg: "文件已重命名" };
        }catch (err) {
            return {success: false, msg:`重命名失败: ${err.message}`};
        }
    });

    ipcMain.handle("clean:image:cache", async (event) =>{
        
        const getMarkdownFiles = async (dirpath)=>{
            const files = await fs.promises.readdir(dirpath);
            let markdownFiles = [];
        
            for (const file of files) {
                const fullPath = path.join(dirpath, file);
                const stat = await fs.promises.stat(fullPath);
        
                if (stat.isDirectory()) {
                    // 如果是目录，递归
                    const nestedFiles = await getMarkdownFiles(fullPath);
                    markdownFiles = markdownFiles.concat(nestedFiles);
                } else if (file.endsWith('.md')) {
                    // 如果是.md文件，保存路径
                    markdownFiles.push(fullPath);
                }
            }
            return markdownFiles
        }
        const postdDir = path.join(appConfig.VITEPRESS_PATH, "posts")
        const markdownFiles = await getMarkdownFiles(postdDir)  // 获取所有的 markdown 文件
        const totalImageSet = new Set();
        const usedImageSet = new Set();
        
        event.sender.send('clean:image:cache:progress', 0, 0);  // 开始进度条
        for (const markdown of markdownFiles){
            const markdownContent = fs.readFileSync(markdown, 'utf-8');
            const imageUrls = markdownContent.match(/!\[.*?\]\((.*?)\)/g);
            const imageUrlsList = imageUrls ? imageUrls.map(img => path.join(path.dirname(markdown), img.match(/\((.*?)\)/)[1])) : [];
            // 遍历所有的已经引用的图片
            imageUrlsList.forEach(image => {
                usedImageSet.add(image)
            })
   
            
            // 遍历所有的目录
            const imageDir = path.join(path.dirname(markdown), "assets/images")
            if (fs.existsSync(imageDir)){
                fs.readdirSync(imageDir).forEach(file => {
                    totalImageSet.add(path.join(imageDir, file))
                })
            }
        }

        let totalDelNum = 0
        let processBar = 0;
        if (totalImageSet.size === 0){
            event.sender.send('clean:image:cache:progress', 100, totalDelNum);
            return
        }

        totalImageSet.forEach(image => {
            processBar += 1
            if (!usedImageSet.has(image)){
                fs.unlinkSync(image)
                totalDelNum += 1
            }
            const progress = Math.floor((processBar / totalImageSet.size) * 100);
            event.sender.send('clean:image:cache:progress', progress, totalDelNum);
        })

    })


        
}